package com.wngbms.netty._12dubbo.service;

import com.wngbms.netty._12dubbo.HelloServerImpl;
import com.wngbms.netty._12dubbo.client.ClientBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    public NettyServerHandler() {
        log.info("init NettyServerHandler");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("msg:{}", msg);

        if (msg.toString().startsWith(ClientBootstrap.providerName)) {
            String hello = new HelloServerImpl().hello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
            ctx.writeAndFlush(hello);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("err", cause);
        ctx.close();
    }
}
